<?php

namespace StudyBuddy\Modules\Linkedin;

/**
 * Class for posting Questions ans Answers
 * to LinkedIn as status updates (share) via Oauth API
 *
 */
class Share extends \StudyBuddy\Observer {

    /**
     * LINKEDIN API Config array
     * a LINKEDIN section from !config.ini
     *
     * @var array
     */
    protected $aConfig;

    public function main() {

        $a = $this->oRegistry->Request->getArray();
        if (empty($a['linkedin'])) {
            d('linkedin checkbox not checked');
            /**
             * Set the preference in Viewer object
             * for that "Post to linkedin" checkbox to be not checked
             * This is just in case it was checked before
             */
            $this->oRegistry->Viewer['b_li'] = false;

            return;
        }

        /**
         * First if this site does not have support for linkedin API
         * OR if User does not have linkedin credentials then
         * there is nothing to do here
         * This is unlikely because user without linkedin credentials
         * will not get to see the checkbox to post to linkedin
         * but still it's better to check just to be sure
         */
        if (!extension_loaded('curl')) {
            d('curl extension not present, exiting');

            return;
        }

        try {

            $this->aConfig = $this->oRegistry->Ini->getSection('LINKEDIN');

            if (empty($this->aConfig)
                    || empty($this->aConfig['OAUTH_KEY'])
                    || empty($this->aConfig['OAUTH_SECRET'])) {
                d('linkedin API not enabled on this site');

                return;
                ;
            }
        } catch (\StudyBuddy\IniException $e) {
            d('Ini Exception: ' . $e->getMessage());

            return;
        }

        if (null === $this->oRegistry->Viewer->getLinkedinToken()) {
            d('User does not have linkedin token');
            return;
        }

        /**
         * Now we know that user checked that checkbox
         * to post content to linkedin
         * and we now going to save this preference
         * in User object
         *
         */
        $this->oRegistry->Viewer['b_li'] = true;
        d('cp');
        switch ($this->eventName) {
            case 'onNewQuestion':
            case 'onNewAnswer':
                $this->post();
                break;
        }
    }

    protected function post() {
        $url = $this->obj->getUrl();
        $label = $this->obj->getTitle();
        $comment = 'I asked this on ' . $this->oRegistry->Ini->SITE_NAME;

        if ($this->obj instanceof \StudyBuddy\Answer) {
            $comment = 'My answer to "' . $label . '"';
        }

        d('$comment: ' . $comment . ' label: ' . $label . ' $url: ' . $url);

        $reward = \StudyBuddy\Points::SHARED_CONTENT;
        $User = $this->oRegistry->Viewer;

        $token = $User->getLinkedinToken();
        $secret = $User->getlinkedinSecret();

        try {
            $oLI = new ApiClient($this->aConfig['OAUTH_KEY'], $this->aConfig['OAUTH_SECRET']);
            $oLI->setUserToken($token, $secret);
        } catch (\Exception $e) {
            e('Error during setup of Linkedin ApiClient object ' . $e->getMessage() . ' in ' . $e->getFile() . ' on ' . $e->getLine());

            return $this;
        }

        $func = function() use ($oLI, $User, $comment, $label, $url, $reward) {
                    try {
                        $oLI->share($comment, $label, $url);
                    } catch (\Exception $e) {
                        return;
                    }

                    $User->setReputation($reward);
                };

        \StudyBuddy\runLater($func);
    }

}
